<?php

declare(strict_types=1);
/**
 * @copyright 深圳市易果网络科技有限公司
 * @version 1.0.0
 * @link https://dayiguo.com
 */

namespace App\Service;

use App\Dao\AdminConfigDao;

use Hyperf\Di\Annotation\Inject;

use Psr\SimpleCache\InvalidArgumentException;

/**
 * 配置管理服务
 *
 * @author 刘兴永(aile8880@qq.com)
 * @package App\Services
 */
class ConfigService extends Service
{
    /**
     * @Inject
     * @var AdminConfigDao
     */
    public $dao;

    /**
     * 获取配置
     *
     * @param string $name
     * @param string $default
     * @return mixed
     */
    public function get(string $name, $default = '')
    {
        try {
            $cache = $this->container->get(\Psr\SimpleCache\CacheInterface::class);

            // 缓存不存在
            if (!$result = $cache->get('config')) {
                // 从数据库拿
                $config_all = $this->dao->getConfig();
                if (!$config_all) return $default;

                $result = [];
                // 判断配置类型
                foreach ($config_all as $conf) {
                    switch ($conf->type) {
                        case 'number':
                            $result[$conf->name] = (int)$conf->value;
                            break;

                        // 开关
                        case 'switch':
                            $result[$conf->name] = $conf->value == '1' ? true : false;
                            break;

                        // 数组
                        case 'array':
                            $result[$conf->name] = [];
                            foreach (explode(PHP_EOL, $conf->value) as $var) {
                                if (strstr(':', $var)) {
                                    $var = explode(':', $var);
                                    $result[$conf->name][$var[0]] = trim($var[1]);
                                } else {
                                    $result[$conf->name][] = $var;
                                }
                            }
                            break;

                        // 标签和复选框
                        case 'tags':
                        case 'checkbox':
                            $result[$conf->name] = explode(',', $conf->value);
                            break;

                        default:
                            $result[$conf->name] = $conf->value;
                    }
                }
                // 存储到缓存
                $cache->set('config', $result);
            }
        }
        catch (InvalidArgumentException $e) {
            // error
            return $default;
        }

        return $result[$name] ?? $default;
    }

    /**
     * 删除配置缓存
     */
    public function delete()
    {
        try {
            $cache = $this->container->get(\Psr\SimpleCache\CacheInterface::class);
            $cache->delete('config');
        }
        catch (InvalidArgumentException $e) {
            // error
        }
    }
}